<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="任务类型" prop="taskType">
        <el-select style="width: 150px" v-model="queryParams.taskType" placeholder="请选择任务类型" clearable>
          <el-option v-for="dict in taskTypeList" :key="dict.value" :label="dict.label"
            :value="dict.value"></el-option>
        </el-select>
      </el-form-item>

       <el-form-item label="分行" prop="subBankCode">
          <treeselect v-model="queryParams.subBankCode" :options="deptOptions" :normalizer="normalizer" placeholder="请选择分行" style="width:300px;"/>
        </el-form-item>

        <el-form-item label="网点" prop="bankCode">
          <treeselect v-model="queryParams.bankCode" :options="deptOptions" :normalizer="normalizer" placeholder="请选择网点" style="width:300px;"/>
        </el-form-item>

      <!-- <el-form-item label="设备IP" prop="equipmentIp">
        <el-input
          v-model="queryParams.equipmentIp"
          placeholder="请输入设备IP"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="场景名称" prop="scenariosTypeList">
        <el-select v-model="queryParams.scenariosTypeList" multiple placeholder="请选择场景" style="width: 150px;">
          <el-option v-for="dict in dict.type.task_scenarios_type" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="设备通道" prop="equipmentChannel">
        <el-input
          v-model="queryParams.equipmentChannel"
          placeholder="请输入设备通道"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->

      <el-form-item label="状态" prop="taskStatus">
          <el-select v-model="queryParams.taskStatus" placeholder="状态" clearable>
            <el-option
              v-for="dict in dict.type.task_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
      </el-form-item>

      <el-form-item label="创建时间">
        <el-date-picker
          v-model="dateRange"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!-- <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['task:detail:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['task:detail:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['task:detail:remove']"
        >删除</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['task:detail:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="20">
        <div style="display: flex;">
          <div v-for="item in reportObj" class="report-item" align="center">
            <dict-tag :options="dict.type.task_status" :value="item.taskStatus"/><div>:</div><div style="line-height: 21px;color: red;">{{ item.value }}</div><div style="margin-right: 5px;">;</div>
          </div>
        </div>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="detailList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="创建时间" width="140" align="center" prop="createTime" />
      <!-- <el-table-column label="分行号" align="center" prop="subBankCode" /> -->
      <el-table-column label="任务类型" align="center" prop="taskType" width="80">
        <template slot-scope="scope">
          <span>{{ scope.row.taskType | handleTaskType }}</span>
        </template>
      </el-table-column>
      <el-table-column label="分行名称" align="center" prop="subBankName" />
      <!-- <el-table-column label="网点号" align="center" prop="bankCode" /> -->
      <el-table-column label="网点名称" align="center" prop="bankName" />
      <!-- <el-table-column label="设备IP" align="center" prop="equipmentIp" /> -->
      <!-- <el-table-column label="设备通道" align="center" prop="equipmentChannel" /> -->
      <el-table-column prop="channelRemark" label="摄像头名称"></el-table-column>
      <el-table-column label="频率类型" align="center" prop="frequencyType">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.task_frequency_type" :value="scope.row.frequencyType"/>
          </template>
      </el-table-column>
      <el-table-column label="采集开始时间" width="140" align="center" prop="startTime" />
      <el-table-column label="采集结束时间" width="140" align="center" prop="startEnd" />
      <el-table-column label="应用场景" align="center" prop="scenariosType">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.task_scenarios_type" :value="scope.row.scenariosType"/>
          </template>
      </el-table-column>
      <!-- <el-table-column label="帧率(帧)" align="center" prop="fps" /> -->
      <!-- <el-table-column label="分割(秒)" align="center" prop="secondMerge" /> -->
      <el-table-column label="状态" align="center" prop="taskStatus">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.task_status" :value="scope.row.taskStatus"/>
          </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <!-- <el-button
            size="mini"
            type="text"
            icon="el-icon-tickets"
            @click="handleUpdate(scope.row)"
          >查看</el-button> -->
          <!-- <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['task:detail:remove']"
          >删除</el-button> -->
          <el-button
            v-if="!!scope.row.msg"
            size="mini"
            type="text"
            icon="el-icon-tickets"
            @click="showMsg(scope.row.msg)"
          >查看错误</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改任务明细对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="分行名称" prop="subBankName">
              <el-input v-model="form.subBankName" disabled placeholder="请输入分行机名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="分行号" prop="subBankCode">
              <el-input v-model="form.subBankCode" disabled placeholder="请输入网点机构号" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
              <el-form-item label="网点名称" prop="bankName">
                <el-input v-model="form.bankName" disabled placeholder="请输入网点机构名称" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="网点号" prop="bankCode">
                <el-input v-model="form.bankCode" disabled placeholder="请输入网点机构号" />
              </el-form-item>
            </el-col>

        </el-row>

        <el-row>
            <el-col :span="12">
              <el-form-item label="设备IP" prop="equipmentIp">
                <el-input v-model="form.equipmentIp" disabled placeholder="请输入设备ip" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="设备通道" prop="equipmentChannel">
                <el-input v-model="form.equipmentChannel" disabled placeholder="请输入设备通道" />
              </el-form-item>
            </el-col>
        </el-row>

        <el-row>
            <el-col :span="12">
              <el-form-item label="采集开始时间" prop="startTime">
                <el-input v-model="form.startTime" disabled placeholder="请输入任务采集开始时间" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="采集结束时间" prop="startEnd">
                  <el-input v-model="form.startEnd" disabled placeholder="请输入任务采集结束时间" />
              </el-form-item>
            </el-col>
        </el-row>

         <el-row>
            <el-col :span="12">
              <el-form-item label="帧率" prop="fps">
                <el-input-number v-model="form.fps" disabled controls-position="right" :min="0" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="分割时间(秒)" prop="secondMerge">
                <el-input-number v-model="form.secondMerge" disabled controls-position="right" :min="0" />
              </el-form-item>
            </el-col>
        </el-row>

        <el-row>
            <el-col :span="12">
              <el-form-item label="应用场景">
                <el-select v-model="form.scenariosTypeList" disabled multiple placeholder="请选择场景">
                  <el-option v-for="dict in dict.type.task_scenarios_type" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="任务频率">
                <el-select v-model="form.frequencyType" disabled placeholder="请选择频率">
                  <el-option v-for="dict in dict.type.task_frequency_type" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
        </el-row>

        <el-row>
            <el-col :span="24">
              <el-form-item label="任务状态">
                <el-select v-model="form.taskStatus" disabled placeholder="任务状态">
                  <el-option v-for="dict in dict.type.task_status" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
        </el-row>


      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog
      title="查看错误信息"
      :visible.sync="errorMsgDialogVisible"
      width="80%">
      <div style="white-space: pre-line; max-height: 600px; overflow-y: auto;word-break: break-all;">{{ errorMsg}}</div>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.app-container {
  ::v-deep.vue-treeselect__placeholder {
    font-size: 13px;
  }
  ::v-deep.vue-treeselect__control {
    height: 30px;
  }
}
</style>

<script>
import { listDetail, getDetail, delDetail, addDetail, updateDetail, queryReport } from "@/api/iis/taskdetail";
import { listDept } from "@/api/system/dept";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "Detail",
  dicts: ['sys_normal_disable','equipment_type','task_frequency_type',"task_scenarios_type","task_status"],
  components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 任务明细表格数据
      detailList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        taskId: null,
        subBankCode: null,
        subBankName: null,
        bankCode: null,
        bankName: null,
        equipmentIp: null,
        equipmentChannel: null,
        equipmentType: null,
        startTime: null,
        startEnd: null,
        frequencyType: null,
        scenariosType: null,
        fps: null,
        secondMerge: null,
        taskStatus: null,
        scenariosTypeList: [],
        taskType: null
      },
      taskTypeList: [
        {
          value: "1",
          label: "总行任务"
        },
        {
          value: "2",
          label: "分行任务"
        },
        {
          value: "3",
          label: "浩云分行"
        }
      ],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      showDialog: false,
        listData: [],
        // 机构树选项
        deptOptions: [],
        deptqueryParams: {
          deptCode: undefined
        },
      dateRange: [],
      reportObj: [],
      errorMsgDialogVisible: false,
      errorMsg: '',
    };
  },
  filters: {
    handleTaskType(taskType) {
      if (taskType === "1") {
        return "总行任务";
      } else if (taskType === "2") {
        return "分行任务";
      } else if (taskType === "3") {
        return "浩云分行";
      }
    },
  },
  created() {
    this.dateRange = [this.formatDate(this.getYesterdatDate()), this.formatDate(new Date())];
    this.getList();
    listDept().then(response => {
          this.deptOptions = this.handleTree(response.data, "deptId");
    });
  },
  methods: {
    showMsg(msg){
      this.errorMsg = msg;
      this.errorMsgDialogVisible = true;
    },
    // 格式化日期格式如：2017-9-19 18:04:33
		formatDate(value, type) {
			// 计算日期相关值
			let time = typeof value == 'number' ? new Date(value) : value;
			let Y = time.getFullYear();
			let M = time.getMonth() + 1;
			let D = time.getDate();
			let h = time.getHours();
			let m = time.getMinutes();
			let s = time.getSeconds();
			let week = time.getDay();
			// 如果传递了type的话
			if (type == undefined) {
				return Y + '-' + (M < 10 ? '0' + M : M) + '-' + (D < 10 ? '0' + D : D);
			}
		},
    getYesterdatDate() {
      let date = new Date();
      date.setTime(date.getTime() - 3600 * 1000 * 24);
      return date;
    },
    /** 查询任务明细列表 */
    getList() {
      this.loading = true;
      let queryParams = Object.assign({}, this.queryParams);
      queryParams = this.addDateRange(queryParams, this.dateRange)
      if (queryParams.scenariosTypeList && queryParams.scenariosTypeList.length > 0) {
        queryParams.scenariosType = queryParams.scenariosTypeList.join(",");
      }
      delete queryParams.scenariosTypeList;
      listDetail(queryParams).then(response => {
        this.detailList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
      queryReport(queryParams).then(response => {
        this.reportObj = response.data
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        taskDetailId: null,
        taskId: null,
        subBankCode: null,
        subBankName: null,
        bankCode: null,
        bankName: null,
        equipmentIp: null,
        equipmentChannel: null,
        equipmentType: null,
        startTime: null,
        startEnd: null,
        frequencyType: null,
        scenariosType: null,
        fps: null,
        secondMerge: null,
        taskStatus: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.taskDetailId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加任务明细";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const taskDetailId = row.taskDetailId || this.ids
      getDetail(taskDetailId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "查看任务明细";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.taskDetailId != null) {
            updateDetail(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addDetail(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const taskDetailIds = row.taskDetailId || this.ids;
      this.$modal.confirm('是否确认删除任务明细编号为"' + taskDetailIds + '"的数据项？').then(function() {
        return delDetail(taskDetailIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      let queryParams = Object.assign({}, this.queryParams);
      queryParams = this.addDateRange(queryParams, this.dateRange)
      if (queryParams.scenariosTypeList && queryParams.scenariosTypeList.length > 0) {
        queryParams.scenariosType = queryParams.scenariosTypeList.join(",");
      }
      delete queryParams.scenariosTypeList;
      this.download('task/detail/export', {
        ...queryParams
      }, `detail_${new Date().getTime()}.xlsx`)
    },
       /** 转换部门数据结构 */
      normalizer(node) {
        if (node.children && !node.children.length) {
          delete node.children;
        }
        return {
          id: node.deptCode,
          label: node.deptName,
          children: node.children
        };
      },
  }
};
</script>
<style lang="scss" scoped>
.report-item{
  display: flex;
}
.custom-long-text-dialog {
  max-height: 600px;
  overflow-y: auto;
  width: 800px;
  white-space: pre-line; /* 保留换行符 */
}
</style>
